package com.banshuibao.bsb_android.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.fragment.AlreadyAnsweredFragment;
import com.banshuibao.bsb_android.fragment.UnAnsweredFragment;

public class AnswerTabActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private ImageView back;
    private RadioGroup radioGroup;
    private FragmentTransaction transaction;
    private FragmentManager manager;
    private UnAnsweredFragment unAnsweredFragment;
    private AlreadyAnsweredFragment alreadyAnsweredFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_answer_tab);
        manager = getSupportFragmentManager();
        initView();
        showFragment(R.id.rb_no_answer);
    }

    private void showFragment(int id) {
        transaction = manager.beginTransaction();
        hideFragment(transaction);
        switch (id) {
            case R.id.rb_no_answer:
                if (unAnsweredFragment == null) {
                    unAnsweredFragment = new UnAnsweredFragment();
                    transaction.add(R.id.tab_frame, unAnsweredFragment, "unAnswer");
                } else {
                    transaction.show(unAnsweredFragment);
                }
                break;
            case R.id.rb_answer:
                if (alreadyAnsweredFragment == null) {
                    alreadyAnsweredFragment = new AlreadyAnsweredFragment();
                    transaction.add(R.id.tab_frame, alreadyAnsweredFragment, "alreadyAnswered");
                } else {
                    transaction.show(alreadyAnsweredFragment);
                }
                break;
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction ft) {
        if (unAnsweredFragment != null) {
            ft.hide(unAnsweredFragment);
        }
        if (alreadyAnsweredFragment != null) {
            ft.hide(alreadyAnsweredFragment);
        }
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back_tab);
        radioGroup = (RadioGroup) findViewById(R.id.rg);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        radioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb_no_answer:
                showFragment(R.id.rb_no_answer);
                break;
            case R.id.rb_answer:
                showFragment(R.id.rb_answer);
                break;
        }
    }
}
